//
//  KDMainwordAddView.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/4.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDMainwordAddView.h"
#import "KDEditeCell.h"
#import "KDEditeCellModel.h"
#import "SVProgressHUD.h"
#import "KDWebEditCell.h"
#import "KDWebSetCellModel.h"
#import "KDMainWordAddViewModel.h"
#define MAX_NUM 4 //cell最多摆几行
#define CELL_HEIGHT 40
@interface KDMainwordAddView ()<UITableViewDelegate, UITableViewDataSource, KDEditeCellDelegate, KDWebEditCellDelegate, UITextFieldDelegate>


@property (weak, nonatomic) UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *wordTf;

/**
 *  添加按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *addBtn;

@property (nonatomic, strong) NSArray *infoArr;
/**
 *  是否只能添加1个
 */
@property (nonatomic, assign, getter=isSingle) BOOL single;
/**
 *  给谁用的：
 */
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, copy) NSString * wordTfPlaceHolder;

@end
@implementation KDMainwordAddView
@synthesize infoArr = _infoArr;
- (NSArray *)infoArr{
    if (!_infoArr) {
        _infoArr = [NSArray new];
    }
    return _infoArr;
}
#pragma mark -板块设置区
+ (instancetype)wordView{
    KDMainwordAddView *wordView = [[[NSBundle mainBundle] loadNibNamed:@"KDMainwordAddView" owner:nil options:nil]lastObject];

    return wordView;
}
- (void)drawRect:(CGRect)rect{
    [super drawRect: rect];
    self.wordTf.delegate = self;
    self.wordTf.returnKeyType = UIReturnKeyDone;
    self.wordTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    //    self.wordTf.delegate = self;
    [self setUpTableView];
}
- (void)setWordTfPlaceHolder:(NSString *)wordTfPlaceHolder{
    _wordTfPlaceHolder = wordTfPlaceHolder;
    self.wordTf.placeholder = self.wordTfPlaceHolder;
}
-(void)setSingle:(BOOL)single{
    _single = single;
    if (single) {
        if (self.infoArr.count) {//如果是只能添加一个的，那么就把已赋值的名字写上去
            KDEditeCellModel *model = self.infoArr[0];
            self.wordTf.text = model.name;
        }
    }
}
- (void)setUpTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , CGRectGetMaxY(self.wordTf.frame), screenW,  self.infoArr.count * CELL_HEIGHT) style:UITableViewStylePlain];
    if (self.infoArr.count >= 4) {//如果关键字的个数多于4个的话，就算4个
        tableView.height = MAX_NUM * CELL_HEIGHT;
        self.height = (MAX_NUM +1) *CELL_HEIGHT;
    }
    self.tableView = tableView;
    KDLog(@"%@",NSStringFromCGRect(self.frame));
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.showsVerticalScrollIndicator = YES;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self addSubview:tableView];

}
- (void)setModel:(KDMainWordAddViewModel *)model{
    _model = model;
    self.type = model.type;
    self.wordTfPlaceHolder = model.wordTfPlaceHolder;
    self.infoArr = model.infoArr;
    self.single = model.single;
}

#pragma mark - 事件点击区
- (IBAction)addBtnClick:(UIButton *)sender {
    //一点➕就弹出下面的printView（已废弃）
//    self.printView_constraint_height.constant = 40;
//    self.printView.hidden = NO;
//    self.tableView.y = CGRectGetMaxY(self.printView.frame);
//    [self layoutIfNeeded];
    
    if (!self.wordTf.text.length) {
        return;
    }
    if (self.single && self.infoArr.count == 1) {//如果是只能添加一个且已经有一个了，就不能再添加了
        [SVProgressHUD showInfoWithStatus:@"名称已存在，请删除后再添加" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.infoArr];
    //获取输入拦中的关键字
    NSMutableString *str = [NSMutableString stringWithString:self.wordTf.text];
    //将汉语的"，"替换为英文的","
    [str replaceOccurrencesOfString:@"，" withString:@"," options:NSCaseInsensitiveSearch range:NSMakeRange(0, str.length)];
    NSArray *arr = [str componentsSeparatedByString:@","];//新添加的关键词
    for (int i = 0 ; i < arr.count; i++) {
        KDEditeCellModel *model = [[KDEditeCellModel alloc]init];
        model.name = arr[i];
        //        model.num = i;
        [tempArr insertObject:model atIndex:0];
    }
    //需要添加的高度：
    CGFloat height = 0.0 ;
    if (self.infoArr.count < MAX_NUM) {//说明之前不够4个，需要加
        if (tempArr.count >= 4) {//加完之后的总数量足够4个了
            height = (MAX_NUM - _infoArr.count) *CELL_HEIGHT;
            self.tableView.height  += height;
            self.height = self.tableView.height + CELL_HEIGHT;
           
        }else{//加完之后的总数量还不足4个
            height = arr.count *CELL_HEIGHT;
            self.tableView.height  += height;
            self.height = self.tableView.height + CELL_HEIGHT;
        }
    }
    self.infoArr = tempArr;
    self.model.infoArr = self.infoArr;
    [self.tableView reloadData];
    if (self.single) {//如果是只能添加一个的，那就让它变状态
        self.addBtn.selected = YES;
    }
    self.tableView.contentSize = CGSizeMake(self.tableView.contentSize.width, self.infoArr.count * CELL_HEIGHT);
    if (_delegate &&[ _delegate respondsToSelector:@selector(KDMainwordAddView:HeightChangeWithIfAdd:AndHeight:)]) {
        [_delegate KDMainwordAddView:self HeightChangeWithIfAdd:YES AndHeight:height];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.infoArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KDEditeCell *cell = [KDEditeCell cellWithTableView:tableView];
    cell.delegate = self;
    cell.model = self.infoArr[indexPath.row];
    cell.model.num = indexPath.row;
    return cell;
}
- (CGFloat) tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELL_HEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELL_HEIGHT;
}

#pragma mark - KDEditeCellDelegate
/**
 *  删除按钮被点击了
 */
- (void)KDEditeCell:(KDEditeCell *)cell deleteBtnClickWithModel:(KDEditeCellModel *)model{//如果删除之前已经是0个了，就不能再删除了
    if (self.infoArr.count == 0) {
        return;
    }
    
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.infoArr];
//    for (KDEditeCellModel *model1 in self.infoArr) {
//        if (model1.num == model.num) {
//            [tempArr removeObject:model1];
//            break;
//        }
//    }
    [tempArr removeObjectAtIndex:cell.model.num];
    self.infoArr = tempArr;
    self.model.infoArr = tempArr;//同时更新模型的数据
    [self.tableView reloadData];
    if (self.single) {//如果是只有一个的话，就改变addBtn的状态
        self.addBtn.selected = NO;
    }
    CGFloat height = 0.0 ;
    if (self.infoArr.count < 4) {//只有当减完之后的总数少于4个的时候才需要减
        self.tableView.height = CELL_HEIGHT *self.infoArr.count;
        self.height =CELL_HEIGHT * (self.infoArr.count +1);
        height = CELL_HEIGHT;
    }
    if (_delegate &&[ _delegate respondsToSelector:@selector(KDMainwordAddView:HeightChangeWithIfAdd:AndHeight:)]) {
        [_delegate KDMainwordAddView:self HeightChangeWithIfAdd:NO AndHeight:height];
    }
}

#pragma mark - KDWebEditCellDelegate
/**
 *  删除按钮被点击了
 */
- (void)KDWebEditCell:(KDWebEditCell *)cell deleteBtnClickWithModel:(KDWebSetCellModel *)model{
    if (self.infoArr.count == 0) {
        return;
    }
    
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.infoArr];
    for (KDWebSetCellModel *model1 in self.infoArr) {
        if (model1.num == model.num) {
            [tempArr removeObject:model1];
            break;
        }
    }
    self.infoArr = tempArr;
     self.model.infoArr = tempArr;//同时更新模型的数据
    [self.tableView reloadData];
    if (self.single) {//如果是只有一个的话，就改变addBtn的状态
        self.addBtn.selected = NO;
    }
    CGFloat height = 0.0;
    if (self.infoArr.count <= 4) {
        self.tableView.height = CELL_HEIGHT *self.infoArr.count;
        self.height =CELL_HEIGHT * (self.infoArr.count +1);
        
    }
    
    if (_delegate &&[ _delegate respondsToSelector:@selector(KDMainwordAddView:HeightChangeWithIfAdd:AndHeight:)]) {
        [_delegate KDMainwordAddView:self HeightChangeWithIfAdd:NO AndHeight:height];
    }
}

#pragma mark - UITextFieldDelegate
/**
 *  当textfield开始输入的时候会调用这个方法
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [textField resignFirstResponder];
}
/**
 *  当textfield开始输入的时候会调用这个方法
 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField.superview.y > screenH * 0.5) {//如果那个textfield的高度在比较下面的话，就让整个View随着键盘的弹出也跟着往上弹。
        if (_delegate  && [_delegate respondsToSelector:@selector(wordTfCoverdByKeyboardWithKDMainwordAddView:)]) {
            [_delegate wordTfCoverdByKeyboardWithKDMainwordAddView:self];
        }
        
    }
    return YES;
}
@end
